<script setup lang="ts">
  import { ArrowDown } from '@element-plus/icons-vue'
  import { ref } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import useEditStrategyService from './service'
  import HButton from '@/components/common/button/HButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'

  const props = defineProps({
    factoryIds: {
      type: Array<string>,
      required: true,
    },
  })

  // 使用服务
  const { updateEnableSpareAuthoriFn, updateEnableFeeAuthoriFn } = useEditStrategyService

  // 策略编辑弹窗状态
  const editStrategyModalVisible = ref(false)

  // 用来控制表单字段的显示
  const strategyFormFieldShow = ref({
    enableSpareAuthori: false,
    enableFeeAuthori: false,
  })

  // 弹窗标题
  const modalTitle = ref('编辑策略')

  // 更新策略事件
  const onUpdateStrategy = (param: string) => {
    if (props.factoryIds.length <= 0) {
      ElMessage({
        type: 'warning',
        message: '请选择商家',
      })
      return
    }
    if (param === '查看配件') {
      modalTitle.value = '编辑查看配件策略'
      editStrategyModalVisible.value = true
      strategyFormFieldShow.value.enableSpareAuthori = true
    }

    if (param === '查看费用') {
      modalTitle.value = '编辑查看费用策略'
      editStrategyModalVisible.value = true
      strategyFormFieldShow.value.enableFeeAuthori = true
    }
  }

  // 是否开启工单配件权限：false-不开启，true-开启
  const enableSpareAuthori = ref(false)

  //是否开启工单费用权限：false-不开启，true-开启
  const enableFeeAuthori = ref(false)

  /**
   * 关闭弹窗方法
   */
  const closeModalFn = () => {
    strategyFormFieldShow.value = {
      enableSpareAuthori: false,
      enableFeeAuthori: false,
    }
    editStrategyModalVisible.value = false
  }

  // 保存策略事件
  const onSaveStrategy = () => {
    const message = () => {
      if (strategyFormFieldShow.value.enableSpareAuthori) {
        return `是否要：“${enableSpareAuthori.value ? '开启' : '关闭'}”选中商家的查看配件权限？`
      }

      if (strategyFormFieldShow.value.enableFeeAuthori) {
        return `是否要：“${enableFeeAuthori.value ? '开启' : '关闭'}”选中商家的查看费用权限？`
      }
    }

    ElMessageBox({
      type: 'warning',
      title: '是否确认修改！',
      message: message(),
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: async (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '更新策略中，请稍等...'
          let res: { code: number; data: object; message: string; success: boolean } | null = null

          // 工单配件权限策略
          if (strategyFormFieldShow.value.enableSpareAuthori) {
            res = await updateEnableSpareAuthoriFn(enableSpareAuthori.value, props.factoryIds)
          }

          // 工单费用权限策略
          if (strategyFormFieldShow.value.enableFeeAuthori) {
            res = await updateEnableFeeAuthoriFn(enableFeeAuthori.value, props.factoryIds)
          }
          if (res) {
            ElMessage({
              type: res.success ? 'success' : 'error',
              message: res.message,
            })
            strategyFormFieldShow.value = {
              enableSpareAuthori: false,
              enableFeeAuthori: false,
            }
            done()
            editStrategyModalVisible.value = false
          }
        } else {
          done()
        }
      },
    })
  }
</script>

<template>
  <div>
    <el-dropdown trigger="click">
      <HButton :disabled="props.factoryIds.length <= 0">
        <span>编辑策略</span>
        <el-icon>
          <ArrowDown />
        </el-icon>
      </HButton>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="onUpdateStrategy('查看配件')">查看配件</el-dropdown-item>
          <el-dropdown-item @click="onUpdateStrategy('查看费用')">查看费用</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <HModal
      @close="closeModalFn"
      :title="modalTitle"
      v-model="editStrategyModalVisible"
      size="small"
    >
      <el-form>
        <el-form-item :label="`当前选中${props.factoryIds.length}个商家`" />

        <!--查看配件策略-->
        <el-form-item v-if="strategyFormFieldShow.enableSpareAuthori" label="查看配件">
          <div style="display: flex; align-items: center; gap: 5px">
            <el-switch v-model="enableSpareAuthori" />
            <span v-if="enableSpareAuthori">开启</span>
            <span v-else>关闭</span>
          </div>
        </el-form-item>

        <!--查看费用策略-->
        <el-form-item v-if="strategyFormFieldShow.enableFeeAuthori" label="查看费用">
          <div style="display: flex; align-items: center; gap: 5px">
            <el-switch v-model="enableFeeAuthori" />
            <span v-if="enableFeeAuthori">开启</span>
            <span v-else>关闭</span>
          </div>
        </el-form-item>
      </el-form>

      <template #footerRight>
        <HButton type="primary" is-modal @click="onSaveStrategy">保存</HButton>
        <HButton is-modal @click="closeModalFn">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<style scoped lang="scss">
  .save_btn {
    background-color: $primaryColor !important;
    border-color: $primaryColor !important;

    &:hover {
      background-color: rgba($primaryColor, 0.8) !important;
      border-color: rgba($primaryColor, 0.8) !important;
    }
  }
</style>
